package io.renren;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class FutureDemo {
    private static class Task implements Callable<String> {

        @Override
        public String call() throws Exception {
            // 模拟真实事务的处理过程，这个过程是非常耗时的。
            Thread.sleep(5000);
            return "call return " + Thread.currentThread().getName();
        }
    }
    @Test
    public void Test() throws Exception {
        FutureDemo demo =new FutureDemo();
//        demo.testComplete();
        demo.testFutrue();
    }

    private void testFutrue() throws Exception{
        List<Future<String>> futures = new ArrayList<Future<String>>();
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("已经提交资源申请");
        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(new Task()));
        }
        for (Future<String> future : futures) {
            if (!future.isDone()) {
                System.out.println("资源还没有准备好");
            }
            System.out.println(future.get());
        }
        executorService.shutdown();
    }

    private void testComplete() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService<String> ecs = new ExecutorCompletionService<>(executorService);
        System.out.println("已经提交资源申请");
        int lenth =10;
        for (int i = 0; i < lenth; i++) {
            ecs.submit(new Task());
        }
        //CompletionService会按处理完后顺序返回结果
        for(int i = 0;i<lenth;i++ ){
            Future<String> f = ecs.take();
            System.out.println(f.get());
        }
        executorService.shutdown();
    }
}
